package com.egao.appo.service.impl;

import com.egao.appo.biz.MessageBiz;
import com.egao.appo.entity.Information;
import com.egao.appo.entity.Message;
import com.egao.appo.service.SequenceService;
import com.egao.common.core.damon.results.PageResult2;
import com.egao.common.core.damon.utils.DateUtil;
import com.egao.common.core.damon.utils.Utils;
import com.egao.common.core.utils.FileServerUtil;
import com.egao.common.core.web.JsonResult;
import com.egao.common.system.controller.FileController;
import com.egao.common.system.entity.User;
//import com.egao.appo.mapper.AppointmentsMapper;
import com.egao.appo.entity.Appointments;
import com.egao.appo.service.AppointmentsService;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;
import com.egao.appo.biz.AppointmentsBiz;
import net.sf.json.JSONObject;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
//import javax.transaction.Transactional;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * 用户资料服务实现类
 * @author : Doman
 * @date : 2021-07-20 09:09:53
 * @version ：1.0
 */
@Service
public class AppointmentsServiceImpl /*extends ServiceImpl<AppointmentsMapper, Appointments> */implements AppointmentsService {

	@Autowired
	private AppointmentsBiz appointmentsBiz;
	@Autowired
	private MessageBiz messageBiz;
	@Autowired
	private SequenceService sequenceService;

    /**
    @Override
    public PageResult<Appointments> listPage(PageParam<Appointments> page) {
        List<Appointments> records = baseMapper.listPage(page);
        return new PageResult<>(records, page.getTotal());
    }

    @Override
    public List<Appointments> listAll(Map<String, Object> page) {
        return baseMapper.listAll(page);
    } */

    @Override
    public JsonResult list(PageResult2<T> page, Appointments appointments, User loginUser)  throws Exception{
        return appointmentsBiz.list(page,appointments,loginUser);
    }

    @Override
    public JsonResult list2(PageResult2<T> page, Appointments appointments, User loginUser)  throws Exception{
        return appointmentsBiz.list2(page,appointments,loginUser);
    }

    @Override
    public JsonResult carousel(PageResult2<T> page, Appointments appointments, User loginUser)  throws Exception{
        JsonResult jr = appointmentsBiz.list2(page,appointments,loginUser);
        if (jr.get("count").equals("0")) {
            page.setPage(1);
            return appointmentsBiz.list2(page,appointments,loginUser);
        }
        return jr;
    }

    @Override
    public JsonResult list(Appointments appointments, User loginUser) {
        return JsonResult.ok().setData(appointmentsBiz.list(appointments,loginUser));
    }

    @Override
    public JsonResult randomInfo() {
        try {
            List<Appointments> ids = appointmentsBiz.findListId();
            int index = new Random().nextInt(ids.size());
            Appointments appointments = new Appointments();
            appointments.setId(ids.get(index).getId());
            return JsonResult.ok().setData(appointmentsBiz.getById(appointments));
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.error("没有数据");
        }
    }

    @Override
    public JsonResult infoByCode(String code) {
        try {
            return JsonResult.ok().setData(appointmentsBiz.infoByCode(code));
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.error("没有数据");
        }
    }

    @Override
    public JsonResult getById(Appointments appointments) {
        return JsonResult.ok().setData(appointmentsBiz.getById(appointments));
    }

    @Override
    public JsonResult getByAppoUserId(String appoUserId) {
        try {
            return JsonResult.ok().setData(appointmentsBiz.getByAppoUserId(appoUserId));
        } catch (EmptyResultDataAccessException e) {
            return JsonResult.ok();
        }
    }

    @Transactional
    @Override
    public JsonResult save(Appointments appointments, User loginUser) {
        appointments.setbCode(sequenceService.genCertCode("appoint", "1", "TS", "-"));
        appointments.setAppoUserId(loginUser.getUserId()+"");
        appointmentsBiz.save(appointments, loginUser);
        return JsonResult.ok("添加成功");
    }

    @Transactional
    @Override
    public JsonResult imPortUser(Appointments appointments, User loginUser) {
        List<Information> informationList = appointmentsBiz.informationList();
        for (Information information : informationList) {
            appointments = new Appointments();
            appointments.setOrganizationId("1");
//            appointments.setAppoUserId("");
            appointments.setName(information.getNickname());
            appointments.setGender(Integer.valueOf(information.getGender()));
            appointments.setPhone(information.getPhone());
            appointments.setHeight(Integer.valueOf(information.getHeight()));
            appointments.setWeight(Integer.valueOf(information.getWeight()));
            appointments.setEducation(information.getEducation());
            appointments.setOccupation(information.getOccupation());
            appointments.setHouse(information.getHouse());
            appointments.setCar(information.getCar());
            appointments.setOnlySon(1);
            appointments.setSelfSituation(information.getComment());
            appointments.setHobby(information.getHobby());
            appointments.setRequirements(information.getRequirement());
            String age = information.getAge();

            age = DateUtil.formatDate(DateUtil.parseDate(age, "yyyy-MM-dd"), "yyyy-MM-dd");
            appointments.setBirthday(age);
            appointments.setMarriage(information.getMarriage());
            appointments.setNativePlace(information.getNativeplace());
            appointments.setLiveCity(information.getAddress());
            appointments.setPhoto(information.getPic());
            appointments.setShowPhoto(0);
//            appointments.setPhotoPrivacy(information.getPic());
            appointments.setDeleted(information.getDeleted());
            appointmentsBiz.save(appointments, loginUser);
        }
        return JsonResult.ok("修改成功");
    }

    @Transactional
    @Override
    public JsonResult update(Appointments appointments, User loginUser) {
        if (Utils.isEmpty(appointments.getExamined())) {
            appointments.setExamined("未审核");
        }
        if (appointmentsBiz.update(appointments, loginUser)) {
            if (Utils.isNotEmpty(appointments.getIdCardPicRemove())) {
                String[] pic = appointments.getIdCardPicRemove().split(",");
                for(String p: pic) {
                    if (p != null && !p.trim().isEmpty()) {
                        File file = new File(FileController.UPLOAD_DIR, p);
                        if (file.delete()) new File(FileController.UPLOAD_DIR, p).delete();
                    }
                }
            }
            return JsonResult.ok("修改成功");
        }
        return JsonResult.error("修改失败");
    }

    @Transactional
    @Override
    public JsonResult updateExamined(Appointments appointments, Message message, User loginUser) {
        if (appointmentsBiz.updateExamined(appointments, loginUser)) {
            if (appointments.getId().length() > 0 && Utils.isNotEmpty(message.getContent())) {
                String[] ids = appointments.getId().split(",");
                String[] keywords = appointments.getKeywords().split(",");
                for(int i = 0; i < ids.length; i ++) {
                    if (ids[i] == null || ids[i].equals("") || keywords[i] == null || keywords[i].equals("")) {
                        break;
                    }
                    message.setReceiverAppoId(Integer.valueOf(ids[i]));
                    message.setReceiverUserId(Integer.valueOf(keywords[i]));
                    message.setType("examined");
                    message.setSendUserId(loginUser.getUserId());
                    messageBiz.save(message, loginUser);
                }
            }
            return JsonResult.ok("修改成功");
        }
        return JsonResult.error("修改失败");
    }

    @Transactional
    @Override
    public JsonResult remove(Appointments appointments, User loginUser) {
        if (appointmentsBiz.remove(appointments, loginUser)) {
            return JsonResult.ok("删除成功");
        }
        return JsonResult.error("删除失败");
    }

}
